<template>
  <div class="equipment">
    <div id="container"></div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import { getequipmentlist, getTitle } from '@/api/echarts';

let map = null;
let distCluster = null;
let pointSimplifierIns = null;

export default {
  name: 'index',
  data() {
    return {
      lat: null, // 初始化为 null，等待接口返回数据
      lng: null, // 初始化为 null，等待接口返回数据
      zoom: 0,
    };
  },
  mounted() {
    this.fetchlnglat(); // 在组件挂载后立即获取标题和初始化地图
  },
  methods: {
    async fetchlnglat() {
      try {
        const title = await getTitle();
        console.log(title, 'title');
        this.lat = parseFloat(title.msg.lat);  // 确保 lat 是有效的数字
        this.lng = parseFloat(title.msg.lng);  // 确保 lng 是有效的数字
        this.zoom = title.msg.zoom;

        // 检查经纬度是否有效
        if (!isNaN(this.lat) && !isNaN(this.lng)) {
          this.initMap(this.lat, this.lng, this.zoom);
        } else {
          console.error('无效的经纬度:', this.lat, this.lng);
        }
      } catch (error) {
        console.error('Error fetching title:', error);
      }
    },

    initMap(lat, lng, zoom) {
      AMapLoader.load({
        key: "f8c954755588cd09132500151dc4d01c",
        version: "2.0",
        plugins: ['AMap.Scale', 'AMap.Marker', 'AMap.InfoWindow', 'AMap.MarkerCluster'],
        AMapUI: {
          version: '1.1',
          plugins: ['overlay/SimpleMarker']
        }
      }).then((AMap) => {
        map = new AMap.Map("container", {
          viewMode: "2D",
          terrain: false,
          zoom: zoom,
          center: [lng, lat], // 使用从接口返回的经纬度
          mapStyle: 'amap://styles/blue',
        });
        this.aMapUiLoad();
      }).catch(e => {
        console.log(`高德地图加载错误提示${e}`);
      });
    },

    initPage(DistrictCluster, PointSimplifier, utils) {
      function MyRender(distClusterIns, opts) {
        MyRender.__super__.constructor.apply(this, arguments);
      }

      utils.inherit(MyRender, DistrictCluster.Render.Default);

      utils.extend(MyRender.prototype, {
        drawFeaturePolygons: function (ctx, polygons, styleOptions, feature, dataItems) {
          MyRender.__super__.drawFeaturePolygons.apply(this, arguments);
          if (dataItems.length > 0) {
            this.drawMyLabel(feature, dataItems);
          }
        },
        _initContainter: function () {
          MyRender.__super__._initContainter.apply(this, arguments);
          this._createCanvas('mylabel', this._container);
        },
        drawMyLabel: function (feature, dataItems) {
          var pixelRatio = this.getPixelRatio(); 
          var containerPos = map.lngLatToContainer(feature.properties.centroid || feature.properties.center);
          var labelCtx = this._getCanvasCxt('mylabel');
          var centerX = containerPos.getX() * pixelRatio,
              centerY = containerPos.getY() * pixelRatio;

          var text = feature.properties.name + ' (' + dataItems.length + ')';
          labelCtx.font = 14 * pixelRatio + 'px 微软雅黑';
          var textMetrics = labelCtx.measureText(text);
          var halfTxtWidth = textMetrics.width / 2;

          // Calculate background rectangle dimensions
          var rectWidth = textMetrics.width + 12 * pixelRatio; // Add padding
          var rectHeight = 22 * pixelRatio;
          var rectX = centerX - halfTxtWidth - 6 * pixelRatio;
          var rectY = centerY - rectHeight / 2;
          var cornerRadius = 5 * pixelRatio;

          // Draw rounded rectangle background with a tech-inspired color
          labelCtx.save();
          labelCtx.beginPath();
          labelCtx.moveTo(rectX + cornerRadius, rectY);
          labelCtx.lineTo(rectX + rectWidth - cornerRadius, rectY);
          labelCtx.quadraticCurveTo(rectX + rectWidth, rectY, rectX + rectWidth, rectY + cornerRadius);
          labelCtx.lineTo(rectX + rectWidth, rectY + rectHeight - cornerRadius);
          labelCtx.quadraticCurveTo(rectX + rectWidth, rectY + rectHeight, rectX + rectWidth - cornerRadius, rectY + rectHeight);
          labelCtx.lineTo(rectX + cornerRadius, rectY + rectHeight);
          labelCtx.quadraticCurveTo(rectX, rectY + rectHeight, rectX, rectY + rectHeight - cornerRadius);
          labelCtx.lineTo(rectX, rectY + cornerRadius);
          labelCtx.quadraticCurveTo(rectX, rectY, rectX + cornerRadius, rectY);
          labelCtx.closePath();

          labelCtx.fillStyle = '#cccccc'; // 使用科技感的蓝色
          labelCtx.fill();

          // Draw text
          labelCtx.fillStyle = '#ffffff';
          labelCtx.textBaseline = 'middle';
          labelCtx.fillText(text, centerX - halfTxtWidth, centerY);

          labelCtx.restore();
        }

      });

      pointSimplifierIns = new PointSimplifier({
        map: map,
        autoSetFitView: false,
        zIndex: 110,
        getPosition: function (item) {
          if (!item || !item.lnglat || isNaN(item.lnglat[0]) || isNaN(item.lnglat[1])) {
            return '';  // 确保返回有效的地理坐标
          }
          return item.lnglat;
        },
        getHoverTitle: function (dataItem, idx) {
          return `<div style="height: 12vh;width: 16vw;background-color:#FFFFFF;margin:0;padding:0;z-index:9999999">
            <h2>第${idx}台设备</h2>
            <p>设备简介</p>
          </div>`;
        },
        renderOptions: {
          pointStyle: {
            width: 6,
            height: 6,
            fillStyle: 'rgba(153, 0, 153, 0.38)'
          },
          hoverTitleStyle: {
            position: 'top'
          }
        }
      });

      distCluster = new DistrictCluster({
        zIndex: 100,
        map: map,
        getPosition: function (item) {
          if (!item || !item.lnglat || isNaN(item.lnglat[0]) || isNaN(item.lnglat[1])) {
            return null;  // 确保返回有效的地理坐标
          }
          return item.lnglat;
        },
        // 使用自定义的引擎类
        renderConstructor: MyRender,
        renderOptions: {
          getClusterMarker: null,
          featureClickToShowSub: true,
          featureStyle: {
            fillStyle: 'rgba(192,192,192,0.5)', // 将中国区域填充为银白色
            strokeStyle: 'rgba(0,0,0,0.5)',
            lineWidth: 1,
            hoverOptions: {
              fillStyle: 'rgba(255,255,255,0.5)',
              lineWidth: 2,
              strokeStyle: 'rgb(255,102,0)'
            }
          },
          getFeatureStyle: function (feature, dataItems) {
            // 对不同区域进行自定义样式设置
            if (feature.properties.name === '中国') {
              return {
                fillStyle: 'rgba(192,192,192,0.5)', // 银白色
                strokeStyle: 'rgba(0,0,0,0.5)',
                lineWidth: 1,
              };
            } else {
              return {
                fillStyle: 'rgba(0, 115, 153, 0.6)', // 默认颜色
                strokeStyle: 'rgba(0, 0, 0, 0.5)',
                lineWidth: 1,
              };
            }
          }
        }
      });

      window.distCluster = distCluster;

      getequipmentlist({ limit: 10000 }).then(res => {
        if (res.code === 0) {
          let data = res.msg;
          let transformedData = data
            .filter(item => {
              return !isNaN(parseFloat(item.lng)) && !isNaN(parseFloat(item.lat)) && item.count !== 0;
            })
            .map(item => {
              let lng = parseFloat(item.lng);
              let lat = parseFloat(item.lat);
              return {
                lnglat: [lng, lat],
                addr: item.addr,
                addrDetail: item.addrDetail,
                addtime: item.addtime,
                agreement: item.agreement,
                detail: item.detail,
                equipmentNo: item.equipmentNo,
                isWorkorder: item.iSWorkorder,
                id: item.id,
                mainBind: item.mainBind,
                status: item.status,
                type: item.type,
                count: item.count
              };
            });

          distCluster.setData(transformedData);
          pointSimplifierIns.setData(transformedData);
        } else {
          console.error('API 返回错误:', res);
        }
      }).catch(error => {
        console.error('请求出错:', error);
      }).finally(() => {
        // loading.close();
      });
    },

    aMapUiLoad() {
      AMapUI.load(['ui/geo/DistrictCluster', 'ui/misc/PointSimplifier', 'lib/$', 'lib/utils'], (DistrictCluster, PointSimplifier, $, utils) => {
        this.initPage(DistrictCluster, PointSimplifier, utils);
      });
    }
  }
};
</script>

<style lang="scss">
.equipment {
  #container {
    width: 100%;
    height: 120vh;
  }

  .amap-ui-district-cluster-region {
    background-color: rgba(192,192,192,0.5) !important; // 银白色背景
  }
}
</style>
